package com.wzt.lianfirecontrol.fragment.my;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.wzt.lianfirecontrol.R;
import com.wzt.lianfirecontrol.activity.BaseActivity;
import com.wzt.lianfirecontrol.activity.ShowFragActivity;
import com.wzt.lianfirecontrol.bean.ConstData;
import com.wzt.lianfirecontrol.bean.recode.user.RoleConstant;
import com.wzt.lianfirecontrol.bean.recode.user.UserInfoModel;
import com.wzt.lianfirecontrol.fragment.BaseFragment;
import com.wzt.lianfirecontrol.http.HttpHelper;
import com.wzt.lianfirecontrol.http.json.ParseJsonData;
import com.wzt.lianfirecontrol.http.Url;
import com.wzt.lianfirecontrol.utils.GildeUtils;
import com.wzt.lianfirecontrol.utils.JSONUtil;
import com.wzt.lianfirecontrol.utils.MinioUtils;
import com.wzt.lianfirecontrol.utils.PreferencesUtils;
import com.wzt.lianfirecontrol.utils.StringUtils;
import com.wzt.lianfirecontrol.utils.ToastUtils;
import com.wzt.lianfirecontrol.utils.Utils;
import com.wzt.lianfirecontrol.view.InitView;

import java.io.File;
import java.util.HashMap;
import java.util.List;

/**
 * 修改用户信息
 */
public class ChangeInfoFragment extends BaseFragment {
    private BaseActivity activity;
    private Bundle bundle;
    private View itemContentView;

    private ImageView iv_user_photo;
    private TextView tv_change_photo;
    private TextView tv_user_account;

    private TextView tv_zhiwu;

    private LinearLayout ll_phone;
    private TextView tv_phone;
    private EditText et_name;
    private ImageView iv_clear_name;
    private EditText et_email;
    private ImageView iv_clear_email;

    private Button bt_submit;

    private static final int CHANGE_USER_INFO_WHAT = 1;

    private String[] imgUrl = new String[]{"", "", ""};
    private boolean isUpdateImg = false;
    private boolean isSubmitSuccess = false;

    private View include_progress_bar;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (null == itemContentView){
            bundle = getArguments();
            activity = getMyActivity();
            itemContentView = inflater.inflate(R.layout.f_change_info, container, false);
            PreferencesUtils.putString(activity, ConstData.CHANGEDPHONE, "");
            initView();
            initData();
        }
        if (itemContentView.getParent() != null) {
            ((ViewGroup) itemContentView.getParent()).removeView(itemContentView);
        }
        return itemContentView;
    }

    private void initView() {
        iv_user_photo = itemContentView.findViewById(R.id.iv_user_photo);
        tv_change_photo = itemContentView.findViewById(R.id.tv_change_photo);
        iv_user_photo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showUpImgPhoto();
            }
        });
        //切换图片
        tv_change_photo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showUpImgPhoto();
            }
        });
        // 用户账号
        tv_user_account = itemContentView.findViewById(R.id.tv_user_account);
        // 职务
        tv_zhiwu = itemContentView.findViewById(R.id.tv_zhiwu);
        // 手机号
        ll_phone = itemContentView.findViewById(R.id.ll_phone);
        tv_phone = itemContentView.findViewById(R.id.tv_phone);
        ll_phone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 切换手机号
                activity.skipToForgetPs("2");
            }
        });

        et_name = itemContentView.findViewById(R.id.et_name);
        iv_clear_name = itemContentView.findViewById(R.id.iv_clear_name);
        iv_clear_name.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                et_name.setText("");
            }
        });
        et_name.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (!StringUtils.isEmpty(et_name.getText().toString())){
                    iv_clear_name.setVisibility(View.VISIBLE);
                }else {
                    iv_clear_name.setVisibility(View.GONE);
                }
            }
        });

        et_email = itemContentView.findViewById(R.id.et_email);
        iv_clear_email = itemContentView.findViewById(R.id.iv_clear_email);
        iv_clear_email.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                et_email.setText("");
            }
        });
        et_email.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (!StringUtils.isEmpty(et_email.getText().toString())){
                    iv_clear_email.setVisibility(View.VISIBLE);
                }else {
                    iv_clear_email.setVisibility(View.GONE);
                }
            }
        });



        bt_submit = itemContentView.findViewById(R.id.bt_submit);
        //

        bt_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                activity.isRefreshing = true;
                // 提交
                initChangeUserInfoHttpHelper();
            }
        });

        include_progress_bar = itemContentView.findViewById(R.id.include_progress_bar);
        InitView.instance().initProgressBar(activity, include_progress_bar);
        //
        List<String> alias = UserInfoModel.getUserInfo(getActivity()).getRoleAlias();
        // 维保人员和维保管理人员只显示预约维保单
        // 组织管理员 ROLE_ORG_MANAGER  先判断是否是组织管理员，是，就只能看，不能操作。不是的话，判断是否是维保人员

        if (alias.contains(RoleConstant.ROLE_ORG_MANAGER)) {
            bt_submit.setVisibility(View.GONE);
            ll_phone.setVisibility(View.GONE);
        }else {
            bt_submit.setVisibility(View.VISIBLE);
            ll_phone.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 显示上传图片弹窗
     */
    private void showUpImgPhoto(){
        if (isUpdateImg){
            ToastUtils.showToast(activity, "正在上传图片");
            return;
        }
        if (activity instanceof ShowFragActivity){
            ((ShowFragActivity)activity).initSubmitPicView(ConstData.PHOTO_CHANG_USER);
        }
    }

    /**
     * 选择图片回传成功动作
     * @param imgUrl
     */
    @Override
    public void imgSuccessAction(File file, String imgUrl, int photoWhat){
        commitPic(file, photoWhat, imgUrl);
    }

    /**
     * 提交图片
     * @param file
     * @param what
     */
    private void commitPic(final File file, final int what, final String img){
        isUpdateImg = true;
        include_progress_bar.setVisibility(View.VISIBLE);
        MinioUtils.upLoadFile(activity, what, file, handler);
    }

    @Override
    public void onResume() {
        super.onResume();
        // 更新手机号
        String changedPhone = PreferencesUtils.getString(activity, ConstData.CHANGEDPHONE, "");
        if (!StringUtils.isEmpty(changedPhone)){
            PreferencesUtils.putString(activity, ConstData.CHANGEDPHONE, "");
            if (null != tv_phone){
                tv_phone.setText(changedPhone);
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (!isSubmitSuccess){
            for (int i = 0; i < imgUrl.length; i++){
                if (!StringUtils.isEmpty(imgUrl[i])){
                    MinioUtils.removeFile(activity, imgUrl[i], handler);
                }
            }
        }
    }

    /**
     * 获取用户信息
     */
    private void initChangeUserInfoHttpHelper() {
        UserInfoModel userInfoModel = UserInfoModel.getUserInfo(activity);
        HashMap<String, Object> url_params = new HashMap<>();
        url_params.put("companyId", userInfoModel.getCompanyId());
        url_params.put("deptId", userInfoModel.getDeptId());
        url_params.put("id", userInfoModel.getId());
        url_params.put("postId", userInfoModel.getPostId());
        url_params.put("status", "1");
        url_params.put("username", userInfoModel.getUsername());
        url_params.put("roleIds", userInfoModel.getRoleIds());
        if (StringUtils.isEmpty(et_name.getText().toString())){
            ToastUtils.showToast(activity, "姓名不能为空");
            return;
        }else {
            url_params.put("realName", et_name.getText().toString());
        }
        if (StringUtils.isEmpty(et_email.getText().toString())){
            ToastUtils.showToast(activity, "邮箱不能为空");
            return;
        }else if (!Utils.checkEmail(et_email.getText().toString())){
            ToastUtils.showToast(activity, "邮箱格式错误");
            return;
        }else {
            url_params.put("email", et_email.getText().toString());
        }
        if (StringUtils.isEmpty(tv_phone.getText().toString())){
            ToastUtils.showToast(activity, "手机号不能为空");
            return;
        }else {
            url_params.put("phone", tv_phone.getText().toString());
        }

        if (!StringUtils.isEmpty(imgUrl[0])) {
            url_params.put("imgUrl", imgUrl[0]);
        }else {
            url_params.put("imgUrl", "");
        }
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put(ConstData.JSONOBJECT, JSONUtil.mapToJSonStr(url_params));
        HttpHelper homeListHttpHelper = new InfoListListHttpHelper(activity, Url.UPDATE_USER_INFO_URL, CHANGE_USER_INFO_WHAT, handler, true, hashMap);
        homeListHttpHelper.setParseJsonData(new InfoListParseJsonData());
        homeListHttpHelper.getHttpRequest(true);
        include_progress_bar.setVisibility(View.VISIBLE);
    }

    private class InfoListListHttpHelper extends HttpHelper{
        public InfoListListHttpHelper(BaseActivity activity, String url, int what, Handler handler, boolean isPost, HashMap<String, String> params) {
            super(activity, url, what, handler, isPost, params);
        }
    }

    protected class InfoListParseJsonData extends ParseJsonData {

        public InfoListParseJsonData() {
        }

        @Override
        public void analyzeResult(String dataStr, Bundle bundle, int what) {
        }
    }

    @Override
    protected void dealWithMyMsgs(Message msg) {
        super.dealWithMyMsgs(msg);
        activity.isRefreshing = false;
        Bundle bundle = msg.getData();
        if ((!bundle.getBoolean(ParseJsonData.REQUEST_OK) ||
                !ParseJsonData.REQUEST_OK_CODE.equals(bundle.getString(ParseJsonData.ERROR_CODE)))){
            include_progress_bar.setVisibility(View.GONE);
            if ((msg.what == CHANGE_USER_INFO_WHAT) && ParseJsonData.REQUEST_OK_CODE.equals(bundle.getString(ParseJsonData.ERROR_CODE))) {
                isSubmitSuccess = true;
                UserInfoModel userInfoModel = UserInfoModel.getUserInfo(activity);
                if (!StringUtils.isEmpty(imgUrl[0])) {
                    userInfoModel.setImgUrl(imgUrl[0]);
                }else {
                    userInfoModel.setImgUrl("");
                }
                userInfoModel.setRealName(et_name.getText().toString());
                userInfoModel.setPhone(tv_phone.getText().toString());
                userInfoModel.setEmail(et_email.getText().toString());
                PreferencesUtils.putString(activity, ConstData.USERINFO, JSONUtil.beanToJson(userInfoModel));
                activity.finish();
            }
            if (msg.what >= ConstData.COMMIT_IMG_WHAT){
                isUpdateImg = false;
            }
            return;
        }

        if (msg.what >= ConstData.COMMIT_IMG_WHAT){
            isUpdateImg = false;
            include_progress_bar.setVisibility(View.GONE);
            switch (msg.what - ConstData.COMMIT_IMG_WHAT){
                case ConstData.PHOTO_CHANG_USER:
                    imgUrl[0] = bundle.getString("fileName");
                    GildeUtils.loadImageCircle(activity, iv_user_photo, imgUrl[0]);
                    break;
            }
        }
    }

    private void initData() {
        UserInfoModel userInfoModel = UserInfoModel.getUserInfo(activity);
        if (!StringUtils.isEmpty(userInfoModel.getImgUrl())) {
            GildeUtils.loadImageCircle(activity, iv_user_photo, userInfoModel.getImgUrl());
            iv_user_photo.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ((ShowFragActivity)activity).setShowImg(userInfoModel.getImgUrl());
                }
            });
        } else {
            iv_user_photo.setImageResource(R.mipmap.user_icon);
        }
        tv_user_account.setText("账号:"+userInfoModel.getUsername());
        tv_zhiwu.setText(userInfoModel.getPostName());
        tv_phone.setText(userInfoModel.getPhone());
        et_name.setText(userInfoModel.getRealName());
        et_email.setText(userInfoModel.getEmail());
    }
}
